package com.kool.kmqtt.server.encoder;

import com.kool.kmqtt.server.packet.Packet;
import com.kool.kmqtt.server.packet.PublishPayload;
import com.kool.kmqtt.server.packet.PublishVariableHeader;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * PUBLISH报文编码器
 */
@Slf4j
public class PublishPacketEncoder implements PacketEncoder {
    @Override
    public byte[] encode(Packet packet) {
        //固定报头编码
        byte[] fixedHeaderBytes = packet.getFixedHeader().toBytes();

        PublishVariableHeader variableHeader = (PublishVariableHeader) packet.getVariableHeader();
        //可变报头编码
        byte[] variableHeaderBytes = variableHeader.toBytes();

        PublishPayload payload = (PublishPayload) packet.getPayload();
        //载荷
        byte[] payloadBytes = payload.getPayload();
        log.debug("报文载荷UTF-8解码：{}",new String(payloadBytes, StandardCharsets.UTF_8));
        //组装报文
        byte[] packetBytes = new byte[fixedHeaderBytes.length + variableHeaderBytes.length + payloadBytes.length];
        System.arraycopy(fixedHeaderBytes, 0, packetBytes, 0, fixedHeaderBytes.length);
        System.arraycopy(variableHeaderBytes, 0, packetBytes, fixedHeaderBytes.length, variableHeaderBytes.length);
        System.arraycopy(payloadBytes, 0, packetBytes, fixedHeaderBytes.length + variableHeaderBytes.length, payloadBytes.length);

        return packetBytes;
    }
}
